package com.javaEE.tes.controllers;

import com.javaEE.tes.dao.dto.StudentClass1;
import com.javaEE.tes.entities.Association;
import com.javaEE.tes.entities.Class1;
import com.javaEE.tes.entities.Student;
import com.javaEE.tes.services.AssociationService;
import com.javaEE.tes.services.Class1Service;
import com.javaEE.tes.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("student")
public class StudentControllers {

    @Autowired
    StudentService studentService;
    @Autowired
    AssociationService associationService;
    @Autowired
    Class1Service class1Service;
    @GetMapping
    public String displayStudent(Model model){
        List<StudentClass1> student= studentService.studentClass1();
        model.addAttribute("students",student);
        return "student/list-student";
    }
    @GetMapping("/new")
    public String displayStudentForm(Model model){

        Student aStudent=new Student();
        List<Association> associations=associationService.getAll();
        List<Class1> class1s=class1Service.getAll();
        model.addAttribute("student",aStudent);
        model.addAttribute("allAssociation",associations);
        model.addAttribute("allClass1",class1s);
        return "student/new-student";
    }


    @PostMapping("/save")
    public String createStudent(Model model, @Valid Student student, Errors errors){

        List<Association> associations=associationService.getAll();
        List<Class1> class1s=class1Service.getAll();
        model.addAttribute("allAssociation",associations);
        model.addAttribute("allClass1",class1s);

        if (errors.hasErrors()) return "student/new-student";

        studentService.save(student);
        return "redirect:/student";
    }







//    @GetMapping("/update")
//    public String displayStudentUpdateForm(@RequestParam(value = "id",required = false,defaultValue = "") long theId, Model model){
//        Student theStudent = studentService.findByStudentId(theId);
//        model.addAttribute("student",theStudent);
//        return "student/new-student";
//
//    }
//    @GetMapping("delete")
//    public String deleteStudent(@RequestParam("id") long theId,Model model) {
//       Student theStudent =studentService.findByStudentId(theId);
//        studentService.delete(theStudent);
//        model.addAttribute("student", theStudent);
//        return "redirect:/student";
//    }
}
